package com.dissertation.action;

import com.alibaba.fastjson.JSON;
import com.dissertation.model.auth.Role;
import com.dissertation.model.auth.User;
import com.dissertation.pojo.CategoryTreeVO;
import com.dissertation.pojo.Message;
import com.dissertation.service.CategoryTreeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;

import static java.util.stream.Collectors.toList;

@RestController
@RequestMapping("/categoryTree")
@CrossOrigin
public class CategoryTreeController {


    @Autowired
    CategoryTreeService categoryTreeService;

    @PostMapping
    Message createCategoryTree(@RequestBody @Validated CategoryTreeVO categoryTreevo , BindingResult result){
        if(result.hasErrors()){
            List<FieldError> fieldErrors = result.getFieldErrors();
            return Message.createErr( JSON.toJSONString( fieldErrors.stream()
                    .map( DefaultMessageSourceResolvable::getDefaultMessage )
                    .collect( toList() ) ) );
        }
         return Message.createSuc(categoryTreeService.save(categoryTreevo));
    }

    @GetMapping
    @CrossOrigin
    Message searchAllCategoryTree(HttpServletResponse response){


        Subject subject = SecurityUtils.getSubject();
        Set<Role> role = ((User)subject.getPrincipal()).getRole();


        return Message.createSuc(categoryTreeService.findAllTree(role));

    }


}
